package com.harmonk.firstscene.ui

import android.app.Application
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material3.Card
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.harmonk.firstscene.R
import com.harmonk.firstscene.db.entity.QuickNote
import com.harmonk.firstscene.ui.model.QuickNoteViewModel
import com.harmonk.firstscene.ui.model.QuickNoteViewModelFactory

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun QuickNoteScreen(
    onBackClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    val context = LocalContext.current
    val quickNoteViewModel: QuickNoteViewModel = viewModel(
        factory = QuickNoteViewModelFactory(context.applicationContext as Application)
    )
    
    val quickNotes by quickNoteViewModel.quickNotes.observeAsState(emptyList())
    
    var showSheetState by remember { mutableStateOf(false) }
    var currentNoteState by remember { mutableStateOf(QuickNote()) }
    
    val sheetState = rememberModalBottomSheetState()
    
    LaunchedEffect(Unit) {
        quickNoteViewModel.loadAllQuickNotes()
    }
    
    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("快捷记事") },
                navigationIcon = {
                    IconButton(onClick = onBackClick) {
                        Icon(
                            imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                            contentDescription = "返回"
                        )
                    }
                }
            )
        },
        modifier = modifier.fillMaxSize(),
        floatingActionButton = {
            FloatingActionButton(
                onClick = {
                    currentNoteState = QuickNote()
                    showSheetState = true
                }
            ) {
                Icon(Icons.Filled.Add, contentDescription = "添加")
            }
        }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
        ) {
            if (quickNotes.isEmpty()) {
                Column(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(16.dp),
                    verticalArrangement = Arrangement.Center,
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Text(
                        text = "暂无快捷记事",
                        style = MaterialTheme.typography.bodyLarge
                    )
                    Text(
                        text = "点击右下角按钮添加",
                        style = MaterialTheme.typography.bodyMedium,
                        modifier = Modifier.padding(top = 8.dp)
                    )
                }
            } else {
                LazyColumn(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(16.dp)
                ) {
                    items(quickNotes) { note ->
                        QuickNoteItem(
                            note = note,
                            onEdit = { 
                                currentNoteState = it
                                showSheetState = true
                            },
                            onDelete = { quickNoteViewModel.deleteQuickNote(it) }
                        )
                    }
                }
            }
        }
        
        if (showSheetState) {
            ModalBottomSheet(
                onDismissRequest = { showSheetState = false },
                sheetState = sheetState
            ) {
                QuickNoteForm(
                    note = currentNoteState,
                    onValueChange = { currentNoteState = it },
                    onSave = {
                        if (currentNoteState.quickNoteId == 0L) {
                            quickNoteViewModel.insertQuickNote(currentNoteState)
                        } else {
                            quickNoteViewModel.updateQuickNote(currentNoteState)
                        }
                        showSheetState = false
                    },
                    onCancel = { showSheetState = false }
                )
            }
        }
    }
}

@Composable
fun QuickNoteItem(
    note: QuickNote,
    onEdit: (QuickNote) -> Unit,
    onDelete: (QuickNote) -> Unit,
    modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier
            .fillMaxWidth()
            .padding(vertical = 4.dp)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = note.note,
                modifier = Modifier.weight(1f)
            )
            Row {
                IconButton(onClick = { onEdit(note) }) {
                    Icon(
                        imageVector = Icons.Filled.Edit,
                        contentDescription = "编辑"
                    )
                }
                IconButton(onClick = { onDelete(note) }) {
                    Icon(
                        imageVector = Icons.Filled.Delete,
                        contentDescription = "删除"
                    )
                }
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun QuickNoteForm(
    note: QuickNote,
    onValueChange: (QuickNote) -> Unit,
    onSave: () -> Unit,
    onCancel: () -> Unit,
    modifier: Modifier = Modifier
) {
    Column(
        modifier = modifier
            .fillMaxWidth()
            .padding(16.dp)
    ) {
        Text(
            text = if (note.quickNoteId == 0L) "添加快捷记事" else "编辑快捷记事",
            style = MaterialTheme.typography.headlineSmall,
            modifier = Modifier.padding(bottom = 16.dp)
        )
        
        OutlinedTextField(
            value = note.note,
            onValueChange = { onValueChange(note.copy(note = it)) },
            label = { Text("记事内容") },
            singleLine = true,
            modifier = Modifier
                .fillMaxWidth()
                .padding(bottom = 16.dp)
        )
        
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.End
        ) {
            TextButton(onClick = onCancel) {
                Text("取消")
            }
            TextButton(onClick = onSave) {
                Text("保存")
            }
        }
    }
}